<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/25
 * 描述:
 */

namespace app\result\goods;

use app\model\goods\GoodsComment;
use app\model\order\Order;
use app\model\order\OrderGoods;
use app\model\user\User;
use app\result\BaseResult;

class GoodsCommentResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new GoodsComment();
    }

    public function api_list($user_id, $args = [])
    {
        $page = intval($args['page'] ?? 1);
        $limit = intval($args['limit'] ?? 20);
        $goods_id = $args['item_id'] ?? 0;
        $type = intval($args['type'] ?? 0);//0=全部，1=好评，2=中评，3=差评
        $where = [];
        $where[] = ['goods_id', '=', $goods_id];
        if ($type == 1) {
            $where[] = ['score', '>=', 4];
        } elseif ($type == 2) {
            $where[] = ['score', '=', 3];
        } elseif ($type == 3) {
            $where[] = ['score', '<=', 2];
        }
        $data = $this->model->data_list($where, '*', 'comment_id desc', $page, $limit);
        if ($data) {
            $data = $data->toArray();
            $data = $this->format_data($data);
        }

        $where = [['goods_id', '=', $goods_id]];
        $statistics = [
            'count_all' => $this->model->data_count($where),
            'count_goods' => $this->model->data_count(array_merge($where, [['score', '>=', 4]])),
            'count_middle' => $this->model->data_count(array_merge($where, [['score', '=', 3]])),
            'count_bad' => $this->model->data_count(array_merge($where, [['score', '<=', 2]])),
        ];
        return self::success_return('success', [
            'list' => $data ?? [],
            'statistics' => $statistics,
        ]);
    }

    public function format_data($data)
    {
        $userIds = array_column($data, 'user_id');
        $allUser = (new User())->data_list_nopage([['user_id', 'in', $userIds]], 'user_id,avatar,username');
        if ($allUser) {
            $allUser = array_column($allUser, null, 'user_id');
        }
        $anonymousAvatar = request()->domain() . '/static/image/niming.png';
        foreach ($data as &$v) {
            $v['images'] = $v['images'] ? json_decode($v['images'], true) : [];
            $v['avatar'] = $allUser[$v['user_id']]['avatar'] ?? $anonymousAvatar;
            $v['username'] = $allUser[$v['user_id']]['username'] ?? '匿名用户';
            if ($v['is_anonymous']) {
                $v['username'] = '匿名用户';
                $v['avatar'] = $anonymousAvatar;
            }
            $v['goods_spec_name'] = $v['goods_spec_name'] ?? '';
            $v['created_at'] = date('Y-m-d', strtotime($v['created_at']));

        }
        unset($v);
        return $data;
    }

    public function comment_ready($user_id, $args): array
    {
        $order_sn = $args['order_sn'] ?? '';
        $order = (new Order())->data_get([['order_sn', '=', $order_sn], ['user_id', '=', $user_id]], 'order_id,order_status');
        if (!$order) {
            return self::error_return('订单不存在');
        }
        if ($order['order_status'] != 3) {
            return self::error_return('订单未完成');
        }
        if (!$order['order_status'] == 4) {
            return self::error_return('订单已评价，感谢您的支持');
        }
        $goods = (new OrderGoods())->data_list_nopage([['order_sn', '=', $order_sn]], 'id,goods_id,goods_spec,goods_name,goods_image,goods_count,goods_price');
        return self::success_return('success', [
            'goods' => $goods ?? [],
        ]);
    }

    public function action($user_id, $args = [])
    {
        $order_sn = $args['order_sn'] ?? 0;
        $formData = $args['formData'] ?? '';
        if (!$order_sn) {
            return self::error_return('参数错误');
        }
        if (!$formData) {
            return self::error_return('请填写评价内容');
        }
        $formData = json_decode(htmlspecialchars_decode($formData), true);
        if (!$formData) {
            return self::error_return('参数错误');
        }
        $order = (new Order())->data_get([['order_sn', '=', $order_sn], ['user_id', '=', $user_id]], 'order_id');
        if (!$order) {
            return self::error_return('订单不存在');
        }
        foreach ($formData as $k => $v) {
            if (!$v['goods_id']) {
                return self::error_return('第' . ($k + 1) . '个参数错误');
            }
            if ($v['score'] < 1 || $v['score'] > 5) {
                return self::error_return('第' . ($k + 1) . '个评分错误');
            }
            $orderGoods = (new OrderGoods())->data_get([['id', '=', $v['order_goods_id']]], 'id,goods_spec');
            if (!$orderGoods) {
                return self::error_return('第' . ($k + 1) . '个商品不存在');
            }
            $v['goods_spec_name'] = $orderGoods['goods_spec_name'];
            $id = (new GoodsComment())->data_add([
                'user_id' => $user_id,
                'score' => $v['score'],
                'content' => $v['content'] ?? "",
                'order_goods_id' => $v['order_goods_id'],
                'goods_id' => $v['goods_id'],
                'order_id' => $order['order_id'],
                'goods_spec_name' => $orderGoods['goods_spec'],
                'images' => $v['image_list'] ? json_encode($v['image_list']) : '',
                'is_anonymous' => !empty($v['is_anonymous']) ? 1 : 0,
            ]);
        }
        if (!empty($id)) {
            (new Order())->data_update([['order_id', '=', $order['order_id']]], ['order_status' => 4]);
        }
        return self::success_return('保存成功');
    }

    public function api_detail($user_id, $args = [])
    {
        return self::success_return('success', [

        ]);
    }

    public function api_delete($user_id, $args = [])
    {
        return self::success_return('删除成功');
    }
}
